package com.thinkgem.jeesite.common.weixin;

import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.task.entity.TpTask;
import com.thinkgem.jeesite.modules.weixin.pageauthorization.AccountConfig;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class SendEmail implements SendMassage{
	
		AccountConfig accountConfig = new AccountConfig();
	    /** 
	     * 获取Session 
	     * @return 
	     */  
	    private static Session getSession() {
	        Properties props = new Properties();  
	        props.put("mail.smtp.host", "smtp.163.com");//设置服务器地址
	        props.put("mail.store.protocol" , "smtp");//设置协议
	        props.put("mail.smtp.port",25);//设置端口
	        props.put("mail.smtp.auth" , true);
	        Authenticator authenticator = new Authenticator() {
	  
	            @Override  
	            protected PasswordAuthentication getPasswordAuthentication() {
	                return new PasswordAuthentication("a846473629@163.com", "kl950811");
	            }  
	              
	        };  
	        Session session = Session.getDefaultInstance(props , authenticator);
	        return session;  
	    }
		@Override
		public TpTask sendMassage(TpTask task) {
			accountConfig.getConfig();
			Session session = getSession();
			try {
				System.out.println("--send--"+task.getContent());
				// Instantiate a message
				Message msg = new MimeMessage(session);

				//Set message attributes
				msg.setFrom(new InternetAddress(AccountConfig.Sender));
				List<InternetAddress> address = new ArrayList<InternetAddress>();
				StringBuilder rst=new StringBuilder();
				for(User user:task.getUser()){
					if(user.getEmail()!=null && user.getEmail()!=""){
						if(user.getEmail().matches("[A-Za-zd]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}")) {
							address.add(new InternetAddress(user.getEmail()));
						}else{
							rst.append(user.getName()+"-->"+"此用户邮箱信息格式不正确！<br/>");
						}
					}else{
						rst.append(user.getEmail()+"-->"+"此用户邮箱信息为空！<br/>");
					}
				}
				task.setResultMsg(rst.toString());
				msg.setRecipients(Message.RecipientType.TO, address.toArray(new InternetAddress[address.size()]));
				msg.setSubject(task.getTitle());
				msg.setSentDate(new Date());
				StringBuilder sb=new StringBuilder();
				sb.append(task.getContent()+"<br/>");
				sb.append("备注：<br>"+task.getRemark()+"<br/>");
				sb.append("<a href="+task.getUrl()+">点此跳转</a>");
				msg.setContent(sb.toString(),"text/html;charset=utf-8");
				Transport.send(msg);
				task.setResultMsg("发送成功！");
				task.setState(9);
			}
			catch (MessagingException mex) {
				mex.printStackTrace();
				task.setState(-1);
				task.setResultMsg(mex.getMessage());
			}
			return task;
		}
}
